/**
 * 地图工具
 */
class HandlerTool {
  viewer: any;
  scene: any;

  height: number;
  longitude: number;
  latitude: number;
  position: any;;
  heading:number;
  pitch:number;
  roll:number;

  constructor(viewer: any){
    this.viewer = viewer;
    this.scene = viewer.scene;
  }

  init(){
    this.getSceneCurrentCameraParamsHandler();
  }

  // 获取场景当前的视角参数|获取当前点击的位置
  getSceneCurrentCameraParamsHandler() {
    const handler = new Cesium.ScreenSpaceEventHandler(this.scene.canvas) // event事件处理程序
    handler.setInputAction((e:any) => {
      const { longitude, latitude, height } = this.getCurrentClickedPosHandler(e);
      this.getCameraParamsHandler()
      // this.addPointAtCurrentClickedPosHandler(longitude, latitude, height)
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
  }

  // 获取当前点击的位置的经纬度高度
  getCurrentClickedPosHandler(e:any) {
    //获取点击位置笛卡尔坐标
    const position = this.scene.pickPosition(e.position);
    //将笛卡尔坐标转化为经纬度坐标
    const cartographic = Cesium.Cartographic.fromCartesian(position)
    const longitude = Cesium.Math.toDegrees(cartographic.longitude)
    const latitude = Cesium.Math.toDegrees(cartographic.latitude)
    let height = cartographic.height
    if (height < 0) {
      height = 0
    }
    this.height = height;
    this.longitude = height;
    this.latitude = height;
    return {
      longitude,
      latitude,
      height,
    }
  }

  // 获取当前场景的视角参数 - 笛卡尔坐标的xyz
  getCameraParamsHandler() {
    const { position, heading, pitch, roll } = this.scene.camera;
    this.position = position;
    this.heading = heading;
    this.pitch = pitch;
    this.roll = roll;
    console.log(position, heading, pitch, roll);
    return {
      position, heading, pitch, roll
    }
  }
  
  // 在当前点击的位置删除之前添加的点位并进行当前点位的添加
  addPointAtCurrentClickedPosHandler(longitude:number, latitude:number, height:number) {
    //首先移除之前添加的点
    // this.viewer.entities.removeAll()
    //在点击位置添加对应点
    this.viewer.entities.add(
      new Cesium.Entity({
        point: new Cesium.PointGraphics({
          color: new Cesium.Color(1, 1, 0),
          pixelSize: 5,
          outlineColor: new Cesium.Color(0, 1, 1),
        }),
        position: Cesium.Cartesian3.fromDegrees(
          longitude,
          latitude,
          height + 1
        ),
      })
    )
  }
}

export default HandlerTool;